/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package server;

import java.net.ConnectException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

// Hlavni trida pro daemona
public class Daemon extends Thread
{
	private static String _ip = "127.0.0.1"; // IP adresa serveru pro daemona
	private static int _port = 2107; // port serveru
	private static ServerSocket _socket; // promenna pro ulozeni serveroveho socketu
	private static List<DaemonClientThread> clients = new ArrayList<DaemonClientThread>(); // seznam pripojenych uzivatelu

	// Hlavni konstruktor
	public Daemon()
	{
		setName("Daemon"); // Nastavi nazev vlakna
	}

	@Override
	public void run()
	{
		try
		{
			// Vytvori serverovy socket, ktery nasloucha na zvolenem portu a IP. 
			// Prostredni parametr je maximalni pocet pripojujicich se uzivatelu (cekajicich na vyrizeni)
			_socket = new ServerSocket(_port, 50, InetAddress.getByName(_ip));
		}
		catch (ConnectException e)
		{
			System.out.println("Daemon: Connecting error.");
			System.exit(-1);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		try
		{
			while (true)
			{
				Socket s = _socket.accept(); // cekani na pripojeni klienta
				DaemonClientThread dct = new DaemonClientThread(s); // vytvoreni nove instance klientskeho vlakna
				clients.add(dct); // pridani uzivatele do seznamu
				dct.start(); // zapnuti jeho vlakna
			}
		}
		catch (Exception e)
		{

		}
		finally
		{
			shutdown(); // vypnuti serveru pro daemona pri chybe
		}
	}

	// Vypnuti serveru
	public void shutdown()
	{
		try
		{
			if (_socket != null)
				_socket.close(); // uzavreni socketu
			
			for (DaemonClientThread dct : getClients()) // odpojeni vsech pripojenych klientu
				dct.close(); 
		}
		catch (Exception e)
		{
			e.printStackTrace(); // vypsani chyby pri vyjimce
		}
		interrupt(); // vypnuti vlakna
	}

	// odebrani klienta ze seznamu
	public static synchronized void RemoveClient(DaemonClientThread dct)
	{
		clients.remove(dct);
	}

	// metoda pro navraceni seznamu pripojenych klientu
	public static synchronized List<DaemonClientThread> getClients()
	{
		return clients;
	}
}
